import { createClient } from 'redis';
import { redisConfig } from './configuration.js';
import log from './logger.js';

let client = null;

// let subscribeClient = null;

async function getClient() {
    if (client == null) {
        console.log('redisConfig',redisConfig);
        client = createClient({url:redisConfig});
        client.on('error', err => log.error('Redis Client Error', err));
        client.on('connect', () => log.info('Redis Client Connected'));
        client.on('ready', () => log.info('Redis Client Ready'));
        client.on('end', () => log.warn('Redis Client End'));
        client.on('reconnecting', () => log.warn('Redis Client reconnecting'));
        await client.connect();
    }
}
// async function getSubscribeClient() {
//     if (subscribeClient == null) {
//         console.log('redisConfig',redisConfig);
//         subscribeClient = createClient({url:redisConfig});
//         subscribeClient.on('error', err => log.error('Redis Client Error', err));
//         subscribeClient.on('connect', () => log.info('Redis Client Connected'));
//         // subscribeClient.on('ready', () => log.info('Redis Client Ready'));
//         // subscribeClient.on('end', () => log.warn('Redis Client End'));
//         // subscribeClient.on('reconnecting', () => log.warn('Redis Client reconnecting'));
//         await subscribeClient.connect();
//     }
// }



//获取24-48小时内的随机失效时间
function getRandomExpireTime() {
    let time = 24 * 60 * 60 + Math.floor(Math.random() * 24 * 60 * 60);
    return time;
}

async function setAutoExpire(key,value) {
    await getClient()
    await client.set(key,value, getRandomExpireTime());
}
async function set(key,value,ExpireTime=null) {
    await getClient()
    if(ExpireTime==null){
        await client.set(key,value);
    }
    else{
        await client.set(key,value, {EX: ExpireTime});
    }

}
async function get(key) {
    await getClient()
    return await client.get(key);
}
// async function subscribe(channel ,callback) {
//     await getSubscribeClient()
//     subscribeClient.subscribe(channel);
//     subscribeClient.on('message', (channel, message) => {
//         callback(channel, message);
//     });
// }
// async function publish(channel,message) {
//     await getSubscribeClient()
//     subscribeClient.publish(channel,message);
// }




export default {
    setAutoExpire,
    set,
    get
    // subscribe,
    // publish

}